#include <iostream>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include "err.hpp"

static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char* argv[])
{
    // 准备工作
    if(argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    // 1. create socket
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        std::cerr << "socket error : " << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }

    // 要不要bind? 要 
    // 要不要自己bind? 不要，因为client要让OS自动给用户进行bind
    // 要不要listen？不要 要不要accept？不需要

    // 2. connect
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &(server.sin_addr));

    int cnt = 5;//尝试重新连接次数
    while(connect(sock, (struct sockaddr*)&server, sizeof(server)) == -1)
    {
        sleep(1);
        std::cout << "正在给你尝试重连,重连次数还有: " << cnt-- << std::endl;
        if(cnt <= 0) break;
    }
    if(cnt <= 0)
    {
        std::cout << "连接失败" << std::endl;
        exit(CONNECT_ERR);
    }

    //连接成功

    while(1)
    {
        //发
        std::string message;
        getline(std::cin, message);

        write(sock, message.c_str(), message.size());

        //收（server的响应）
        char buffer[1024];
        ssize_t n = read(sock, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            //显示响应信息
            std::cout << "server>#" << buffer << std::endl;
        }
        else if(n == 0)
        {
            //读到了文件末尾，说明连接已关闭
            std::cout << "server quit" << std::endl;
            break;
        }
        else{
            std::cerr << "read error: " << strerror(errno) << std::endl;
            break;
        }

    }

    close(sock);
    return 0;
}